/** @jsx jsx */ import {
  keyframes,
  ClassNames,
  css,
  jsx,
} from '@emotion/react';
//not use
import classNames from 'classnames';
import webviews from '../webviews.js';
import settings from '../util/settings/settings.js';
import modalMode from '../modalMode.js';
import ProcessSpawner from '../util/process.js';
import React from 'react';

const fs = window.require('fs');
const path = window.require('path');
const css_global = css`
  max-width: 550px;
  padding: 1em;

  #manager-setup-heading {
    font-size: 1.6em;
  }

  .drag-and-drop-box {
    height: 200px;
    width: 100%;
    border-width: 2px;
    border-style: dashed;
    border-color: #2eb9ce;
    border-radius: 10px;
    padding: 15px;
    display: flex;
    justify-content: center;
    align-items: center;
    text-align: center;
  }

  #manager-setup-dialog .buttons {
    float: right;
  }

  #manager-setup-dialog input[type='button'] {
    padding: 0.2em;
  }
`;
export default class SetupDialog extends React.Component {
  constructor() {
    super();
    // this.ref_menuButton= React.createRef();
    this.state = {
      hidden: true,
      credentials: [],
      manager_setup_heading: '',
      password_manager_setup_link: '',
      password_manager_setup_link_installer: '',
    };
    SetupDialog.current = this;
    this.manager = null;
    this.setupMode = null;
    this.installerCompletionTimeout = null;
  }
  show = (manager) => {
    this.manager = manager;
    this.setupMode = manager.getSetupMode();
    this.setState({
      manager_setup_heading: l('passwordManagerSetupHeading').replace(
        '%p',
        manager.name
      ),
      // password_manager_setup_link:l('passwordManagerSetupLink').replace('%p', manager.name),
      // password_manager_setup_link_installer:l('passwordManagerSetupLinkInstaller').replace('%p', manager.name)
    });

    if (this.setupMode === 'installer') {
      this.setState({
        primaryInstructions_hidden: true,
        secondaryInstructions_hidden: false,
      });
      this.installerCompletionTimeout = setTimeout(
        waitForInstallerComplete,
        2000
      );
    } else {
      this.setState({
        primaryInstructions_hidden: false,
        secondaryInstructions_hidden: true,
      });
    }

    modalMode.toggle(true, {
      onDismiss: function () {
        settings.set('passwordManager', null);
        this.hide();
      },
    });
    this.setState({ hidden: false });
    webviews.requestPlaceholder('managerSetup');
  };
  hide = () => {
    this.manager = null;
    this.setupMode = null;
    clearTimeout(this.installerCompletionTimeout);
    this.installerCompletionTimeout = null;

    modalMode.toggle(false);
    this.setState({ hidden: true });
    webviews.hidePlaceholder('managerSetup');
  };
  render() {
    return (
      <div
        css={css_global}
        className="modal"
        id="manager-setup-dialog"
        hidden={this.state.hidden}
      >
        <h3 className="modal-title" id="manager-setup-heading">
          {this.state.manager_setup_heading}
        </h3>
        <button
          onClick={() => {
            settings.set('passwordManager', null);
            this.hide();
          }}
          id="manager-setup-close"
          className="modal-close-button i carbon:close"
        ></button>

        <div id="manager-setup-instructions-primary">
          <div
            className="light-fade"
            data-string="passwordManagerSetupStep1"
            data-allowhtml
          ></div>
          <div className="spacer"></div>
          <div
            className="light-fade"
            data-string="passwordManagerSetupStep2"
            data-allowhtml
          ></div>
        </div>

        <div id="manager-setup-instructions-secondary">
          <div
            className="light-fade"
            data-string="passwordManagerInstallerSetup"
            data-allowhtml
          ></div>
        </div>

        <div className="spacer"></div>

        <div
          id="manager-setup-drop-box"
          className="drag-and-drop-box"
          data-string="passwordManagerSetupDragBox"
        ></div>

        <div className="spacer"></div>
        <div className="spacer"></div>

        <div className="buttons">
          <input
            type="button"
            onClick={() => {
              settings.set('passwordManager', null);
              this.hide();
            }}
            id="manager-setup-disable"
            data-value="disableAutofill"
          />
        </div>
      </div>
    );
  }
  static initialize = () => {
    SetupDialog.current.initialize();
  };
  initialize = () => {
    // dragBox.ondragover = () => {
    //   return false
    // }
    // dragBox.ondragleave = () => {
    //   return false
    // }
    // dragBox.ondragend = () => {
    //   return false
    // }
    // dragBox.ondrop = (e) => {
    //   e.preventDefault()
    //   if (e.dataTransfer.files.length === 0) {
    //     return
    //   }
    //   dragBox.innerHTML = l('passwordManagerSetupInstalling')
    //   const filePath = e.dataTransfer.files[0].path
    //   // try to filter out anything that isn't an executable (note: not 100% accurate)
    //   if (e.dataTransfer.files[0].type !== '' && !e.dataTransfer.files[0].name.endsWith('.exe')) {
    //     dragBox.innerHTML = l('passwordManagerSetupRetry')
    //     return
    //   }
    //   if (this.setupMode === 'installer') {
    //     this.launchInstaller(filePath, window.platformType)
    //   } else {
    //     this.install(filePath).then(this.afterInstall)
    //   }
    //   return false
    // }
  };
  waitForInstallerComplete = () => {
    this.manager.checkIfConfigured().then(function (configured) {
      if (configured) {
        this.afterInstall();
        this.installerCompletionTimeout = null;
      } else {
        this.installerCompletionTimeout = setTimeout(
          waitForInstallerComplete,
          2000
        );
      }
    });
  };

  // Install the tool into the Min user folder.
  install = (filePath, callback) => {
    return new Promise((resolve, reject) => {
      try {
        const toolsDir = path.join(window.globalArgs['home'], 'tools');
        if (!fs.existsSync(toolsDir)) {
          fs.mkdirSync(toolsDir);
        }

        const targetFilePath = this.manager.getLocalPath();
        fs.createReadStream(filePath)
          .pipe(fs.createWriteStream(targetFilePath))
          .on('finish', function () {
            fs.chmodSync(targetFilePath, '755');
            resolve(targetFilePath);
          })
          .on('error', function (error) {
            reject(error);
          });
      } catch (e) {
        reject(e);
      }
    });
  };
  // Launch installer file.
  launchInstaller = (filePath, platform) => {
    if (platform === 'mac') {
      return new ProcessSpawner('open', [filePath]).execute();
    } else {
      return new ProcessSpawner(filePath).execute();
    }
  };

  afterInstall = (toolPath) => {
    var signInFields = [
      { placeholder: l('email'), id: 'email', type: 'text' },
      { placeholder: l('password'), id: 'password', type: 'password' },
      { placeholder: l('secretKey'), id: 'secretKey', type: 'password' },
    ].filter((f) => this.manager.getSignInRequirements().includes(f.id));

    // Verify the tool by trying to use it to unlock the password store.
    const data = ipc.sendSync('prompt', {
      text: l('passwordManagerSetupSignIn'),
      values: signInFields,
      ok: l('dialogConfirmButton'),
      cancel: l('dialogSkipButton'),
      width: 500,
      height: 220,
    });

    for (const key in data) {
      if (data[key] === '') {
        throw new Error('no credentials entered');
      }
    }

    this.manager
      .signInAndSave(data, toolPath)
      .then(() => {
        this.hide();
      })
      .catch(function (e) {
        console.warn(e);
        if (this.setupMode === 'installer') {
          // show the dialog again
          afterInstall();
        } else {
          // Cleanup after we failed.
          const targetFilePath = this.manager.getLocalPath();
          if (fs.existsSync(targetFilePath)) {
            fs.unlinkSync(targetFilePath);
          }

          const message = (e.error || '').replace(/\n$/gm, '');
          dragBox.innerHTML =
            l('passwordManagerSetupUnlockError') +
            message +
            ' ' +
            l('passwordManagerSetupRetry');
        }
      });
  };
}
// SetupDialog.initialize()
